package control

import (
	"Sales_system/Dao"
	"Sales_system/pkg/app"
	"Sales_system/pkg/e"
	"Sales_system/services"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/unknwon/com"
)

func Getorder(c *gin.Context)  {
	err, info, total := services.Getallorders()
	//fmt.Println(info);
	if err !=nil{
		app.Error(c,e.ERROR,err,err.Error())
		return
	}
	app.OK(c, map[string]interface{}{"value": info, "total": total},"OK")
}

func Addorder(c *gin.Context)  {
	b, _ := c.GetRawData()
	var m map[string]string
	_ = json.Unmarshal(b, &m)
	new_order := Dao.Orders{
		Order_id: m["order_id"],
		Consumer_id :com.StrTo(m["consumer_id"]).MustInt(),
		Goods_id: m["goods_id"],
		Order_date: m["order_date"],
		Order_request: m["order_request"],
		Order_is_availabe : com.IsDir(m["order_is_availabe"]),
		Order_freight: com.StrTo(m["order_freight"]).MustInt(),
		//Is_del: com.IsDir(m["is_del"]),
	}

	if new_order.Order_id == "" {
		app.INFO(c, 30000, "参数非法")
		return
	}

	err := services.Addorders(new_order)
	if err !=nil{
		app.Error(c,e.ERROR,err,err.Error())
		return
	}
	app.OK(c, map[string]interface{}{},"添加成功")
}


func Updatelorder(c *gin.Context){
	b, _ := c.GetRawData()
	var m map[string]string
	_ = json.Unmarshal(b, &m)
	if m["order_id"] == ""{
		app.INFO(c, 30000, "参数非法")
		return
	}

	new_order := Dao.Orders{
		Order_id: m["order_id"],
		Consumer_id: com.StrTo(m["consumer_id"]).MustInt(),
		Goods_id: m["goods_id"],
		Order_date:m["order_date"],
		Order_request: m["order_request"],
		Order_is_availabe: com.IsDir(m["order_is_availabe"]),
		Order_freight: com.StrTo(m["order_freight"]).MustInt(),
		//Is_del: com.IsDir(m["is_del"]),
	}

	err := services.Updateorders(new_order)
	if err !=nil{
		app.Error(c,e.ERROR,err,err.Error())
		return
	}
	app.OK(c, map[string]interface{}{},"更新成功")
}



func Delorder(c *gin.Context){
	var id = ""
	b, _ := c.GetRawData()
	var m map[string]string
	_ = json.Unmarshal(b, &m)
	id = m["Order_id"]
	if id == ""{
		app.INFO(c,30001,"参数错误")
		return
	}

	err := services.Deleteorders(id)
	if err !=nil{
		app.Error(c,e.ERROR,err,err.Error())
		return
	}

	app.OK(c, map[string]interface{}{},"删除成功")
}